import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

/// 连接服务
/// 负责检测和管理设备网络连接状态
class ConnectivityService extends GetxService {
  // 连接类型
  static const String none = 'none';
  static const String wifi = 'wifi';
  static const String mobile = 'mobile';
  static const String ethernet = 'ethernet';
  static const String bluetooth = 'bluetooth';
  
  // 连接状态流控制器
  final StreamController<String> _connectivityStreamController = 
      StreamController<String>.broadcast();
  
  // 公开的连接状态流
  Stream<String> get onConnectivityChanged => _connectivityStreamController.stream;
  
  // 当前连接状态
  String _connectionStatus = none;
  String get connectionStatus => _connectionStatus;
  
  // 连接检查计时器
  Timer? _connectivityTimer;
  
  @override
  void onInit() {
    super.onInit();
    
    // 初始化连接状态检测
    _initConnectivity();
    
    // 定期检查连接状态
    _connectivityTimer = Timer.periodic(
      const Duration(seconds: 30), 
      (_) => _checkConnectivityPeriodically()
    );
  }
  
  @override
  void onClose() {
    _connectivityStreamController.close();
    _connectivityTimer?.cancel();
    super.onClose();
  }
  
  /// 初始化连接状态检测
  Future<void> _initConnectivity() async {
    try {
      // 模拟获取连接状态
      // 实际应用中，应该使用connectivity_plus或network_info_plus包
      await Future.delayed(const Duration(seconds: 1));
      _updateConnectionStatus(wifi);
    } catch (e) {
      debugPrint('初始化连接状态失败: $e');
      _updateConnectionStatus(none);
    }
  }
  
  /// 更新连接状态
  void _updateConnectionStatus(String status) {
    if (_connectionStatus != status) {
      _connectionStatus = status;
      _connectivityStreamController.add(status);
    }
  }
  
  /// 检查当前连接状态
  Future<String> checkConnectivity() async {
    try {
      // 模拟网络检查
      // 实际应用中，应该使用connectivity_plus或network_info_plus包
      final isConnected = await _checkConnection();
      final status = isConnected ? wifi : none;
      _updateConnectionStatus(status);
      return status;
    } catch (e) {
      debugPrint('检查连接状态失败: $e');
      _updateConnectionStatus(none);
      return none;
    }
  }
  
  /// 定期检查连接状态
  Future<void> _checkConnectivityPeriodically() async {
    await checkConnectivity();
  }
  
  /// 模拟连接检查
  Future<bool> _checkConnection() async {
    try {
      // 模拟网络连接检查
      // 实际应用中，应该执行真实的网络连接测试
      await Future.delayed(const Duration(milliseconds: 500));
      return true;
    } catch (e) {
      return false;
    }
  }
  
  /// 判断是否已连接
  bool get isConnected => _connectionStatus != none;
  
  /// 判断是否使用WiFi连接
  bool get isWifi => _connectionStatus == wifi;
  
  /// 判断是否使用移动数据连接
  bool get isMobile => _connectionStatus == mobile;
} 